package com.zlsy.thread.atomic;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author zhouliang
 * @date 2020/8/11 19:22
 * 演示AtomicInteger的基本用法，并且对比非原子类。
 */
public class AtomicIntegerDemo implements Runnable {

    private static final AtomicInteger atomic = new AtomicInteger();
    private static volatile int count = 0;

    public static void main(String[] args) throws InterruptedException {
        AtomicIntegerDemo r = new AtomicIntegerDemo();
        Thread thread1 = new Thread(r);
        Thread thread2 = new Thread(r);

        thread1.start();
        thread2.start();

        thread1.join();
        thread2.join();

        System.out.println(String.format("原子类的结果:%s", atomic.get()));
        System.out.println(String.format("普通变量的结果:%s", count));
    }

    public void incrementAndGet() {
        atomic.incrementAndGet();
    }

    public void incrementCount() {
        count++;
    }

    @Override
    public void run() {
        for (int i = 0; i < 10000; i++) {
            incrementAndGet();
            incrementCount();
        }
    }
}
